"""
配置设置模块 - 提供全局配置和设置
"""

import os
import json
from typing import Dict, Any
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# OpenAI配置
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4-turbo")
OPENAI_TEMPERATURE = float(os.getenv("OPENAI_TEMPERATURE", "0.7"))

# 应用配置
APP_TITLE = "智能量化分析平台"
APP_DESCRIPTION = "基于LangGraph和AKShare的智能量化分析系统"

# 默认值
DEFAULT_STOCK_CODE = "000001"
DEFAULT_STOCK_NAME = "平安银行"
DEFAULT_ANALYSIS_TYPE = "估值分析"
DEFAULT_TIME_RANGE = "1年"

# 时间范围映射（天数）
TIME_RANGE_DAYS = {
    "1个月": 30,
    "3个月": 90,
    "6个月": 180,
    "1年": 365,
    "3年": 365*3,
    "5年": 365*5,
    "全部": 365*10
}

# 复权方式映射
ADJUST_METHODS = {
    "前复权": "qfq",
    "后复权": "hfq",
    "不复权": ""
}

# 数据频率映射
DATA_PERIODS = {
    "日线": "daily",
    "周线": "weekly",
    "月线": "monthly"
}

def load_config(config_path: str = None) -> Dict[str, Any]:
    """
    加载配置文件
    
    参数:
        config_path: 配置文件路径，默认为~/.fdas/config.json
        
    返回:
        配置字典
    """
    # 设置默认配置文件路径
    if config_path is None:
        home_dir = os.path.expanduser("~")
        config_path = os.path.join(home_dir, ".fdas", "config.json")
    
    # 检查配置文件是否存在
    if not os.path.exists(config_path):
        return {}
    
    try:
        # 读取配置文件
        with open(config_path, "r", encoding="utf-8") as f:
            config = json.load(f)
        
        return config
    except Exception as e:
        print(f"加载配置文件失败: {str(e)}")
        return {}

def save_config(config: Dict[str, Any], config_path: str = None) -> bool:
    """
    保存配置文件
    
    参数:
        config: 配置字典
        config_path: 配置文件路径，默认为~/.fdas/config.json
        
    返回:
        是否成功
    """
    # 设置默认配置文件路径
    if config_path is None:
        home_dir = os.path.expanduser("~")
        config_dir = os.path.join(home_dir, ".fdas")
        config_path = os.path.join(config_dir, "config.json")
    
    try:
        # 创建配置目录
        os.makedirs(os.path.dirname(config_path), exist_ok=True)
        
        # 写入配置文件
        with open(config_path, "w", encoding="utf-8") as f:
            json.dump(config, f, ensure_ascii=False, indent=4)
        
        return True
    except Exception as e:
        print(f"保存配置文件失败: {str(e)}")
        return False

# 加载用户配置
user_config = load_config()

# 更新配置
if user_config:
    # 更新OpenAI配置
    if "openai" in user_config:
        openai_config = user_config["openai"]
        if "api_key" in openai_config and openai_config["api_key"]:
            OPENAI_API_KEY = openai_config["api_key"]
        if "base_url" in openai_config and openai_config["base_url"]:
            OPENAI_BASE_URL = openai_config["base_url"]
        if "model" in openai_config and openai_config["model"]:
            OPENAI_MODEL = openai_config["model"]
        if "temperature" in openai_config:
            OPENAI_TEMPERATURE = float(openai_config["temperature"])
    
    # 更新应用配置
    if "app" in user_config:
        app_config = user_config["app"]
        if "title" in app_config and app_config["title"]:
            APP_TITLE = app_config["title"]
        if "description" in app_config and app_config["description"]:
            APP_DESCRIPTION = app_config["description"]